home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus 2002 #3 / Amiga Plus CD - 2002 - No. 03.iso / AmigaPlus / Tools / Development / stunnel-4.04 / _src / src / client.c next >
Encoding:
C/C++ Source or Header  |  2003-01-01  |  30.0 KB  |  918 lines

  1. /*
  2.  *   stunnel       Universal SSL tunnel
  3.  *   Copyright (c) 1998-2003 Michal Trojnara <Michal.Trojnara@mirt.net>
  4.  *                 All Rights Reserved
  5.  *
  6.  *   This program is free software; you can redistribute it and/or modify
  7.  *   it under the terms of the GNU General Public License as published by
  8.  *   the Free Software Foundation; either version 2 of the License, or
  9.  *   (at your option) any later version.
  10.  *
  11.  *   This program is distributed in the hope that it will be useful,
  12.  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  *   GNU General Public License for more details.
  15.  *
  16.  *   You should have received a copy of the GNU General Public License
  17.  *   along with this program; if not, write to the Free Software
  18.  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  *
  20.  *   In addition, as a special exception, Michal Trojnara gives
  21.  *   permission to link the code of this program with the OpenSSL
  22.  *   library (or with modified versions of OpenSSL that use the same
  23.  *   license as OpenSSL), and distribute linked combinations including
  24.  *   the two.  You must obey the GNU General Public License in all
  25.  *   respects for all of the code used other than OpenSSL.  If you modify
  26.  *   this file, you may extend this exception to your version of the
  27.  *   file, but you are not obligated to do so.  If you do not wish to
  28.  *   do so, delete this exception statement from your version.
  29.  */
  30.  
  31. /* Undefine if you have problems with make_sockets() */
  32. #define INET_SOCKET_PAIR
  33.  
  34. #include "common.h"
  35. #include "prototypes.h"
  36.  
  37. #ifndef SHUT_RD
  38. #define SHUT_RD 0
  39. #endif
  40. #ifndef SHUT_WR
  41. #define SHUT_WR 1
  42. #endif
  43. #ifndef SHUT_RDWR
  44. #define SHUT_RDWR 2
  45. #endif
  46.  
  47. /* TCP wrapper */
  48. #ifdef USE_LIBWRAP
  49. #include <tcpd.h>
  50. int allow_severity=LOG_NOTICE;
  51. int deny_severity=LOG_WARNING;
  52. #endif
  53.  
  54. #if SSLEAY_VERSION_NUMBER >= 0x0922
  55. static unsigned char *sid_ctx=(unsigned char *)"stunnel SID";
  56.     /* const allowed here */
  57. #endif
  58.  
  59. extern SSL_CTX *ctx; /* global SSL context defined in ssl.c */
  60.  
  61. static int do_client(CLI *);
  62. static int init_local(CLI *);
  63. static int init_remote(CLI *);
  64. static int init_ssl(CLI *);
  65. static int transfer(CLI *);
  66. static void cleanup(CLI *, int);
  67.  
  68. static void print_cipher(CLI *);
  69. static int auth_libwrap(CLI *);
  70. static int auth_user(CLI *);
  71. static int connect_local(CLI *c);
  72. #ifndef USE_WIN32
  73. static int make_sockets(int [2]);
  74. #endif
  75. static int connect_remote(CLI *c);
  76. static void reset(int, char *);
  77.  
  78. int max_clients;
  79. #ifndef USE_WIN32
  80. int max_fds;
  81. #endif
  82.  
  83. /* Allocate local data structure for the new thread */
  84. void *alloc_client_session(LOCAL_OPTIONS *opt, int rfd, int wfd) {
  85.     CLI *c;
  86.  
  87.     c=calloc(1, sizeof(CLI));
  88.     if(!c) {
  89.         log(LOG_ERR, "Memory allocation failed");
  90.         return NULL;
  91.     }
  92.     c->opt=opt;
  93.     c->local_rfd.fd=rfd;
  94.     c->local_wfd.fd=wfd;
  95.     return c;
  96. }
  97.  
  98. void *client(void *arg) {
  99.     CLI *c=arg;
  100.  
  101.     log(LOG_DEBUG, "%s started", c->opt->servname);
  102. #ifndef USE_WIN32
  103.     if(c->opt->option.remote && c->opt->option.program)
  104.         c->local_rfd.fd=c->local_wfd.fd=connect_local(c);
  105.             /* connect and exec options specified together */
  106.             /* spawn local program instead of stdio */
  107. #endif
  108.     c->remote_fd.fd=-1;
  109.     c->ssl=NULL;
  110.     cleanup(c, do_client(c));
  111. #ifdef USE_FORK
  112.     if(!c->opt->option.remote) /* 'exec' specified */
  113.         exec_status(); /* null SIGCHLD handler was used */
  114. #else
  115.     enter_critical_section(CRIT_CLIENTS); /* for multi-cpu machines */
  116.     log(LOG_DEBUG, "%s finished (%d left)", c->opt->servname,
  117.         --num_clients);
  118.     leave_critical_section(CRIT_CLIENTS);
  119. #endif
  120.     free(c);
  121.     return NULL;
  122. }
  123.  
  124. static int do_client(CLI *c) {
  125.     int result;
  126.  
  127.     if(init_local(c))
  128.         return -1;
  129.     if(!options.option.client && !c->opt->protocol) {
  130.         /* Server mode and no protocol negotiation needed */
  131.         if(init_ssl(c))
  132.             return -1;
  133.         if(init_remote(c))
  134.             return -1;
  135.     } else {
  136.         if(init_remote(c))
  137.             return -1;
  138.         if(negotiate(c)<0) {
  139.             log(LOG_ERR, "Protocol negotiations failed");
  140.             return -1;
  141.         }
  142.         if(init_ssl(c))
  143.             return -1;
  144.     }
  145.     result=transfer(c);
  146.     log(LOG_NOTICE,
  147.         "Connection %s: %d bytes sent to SSL, %d bytes sent to socket",
  148.          result ? "reset" : "closed", c->ssl_bytes, c->sock_bytes);
  149.     return result;
  150. }
  151.  
  152. static int init_local(CLI *c) {
  153.     int addrlen;
  154.  
  155.     addrlen=sizeof(c->addr);
  156.  
  157.     if(getpeername(c->local_rfd.fd, (struct sockaddr *)&c->addr, &addrlen)<0) {
  158.         strcpy(c->accepting_address, "NOT A SOCKET");
  159.         c->local_rfd.is_socket=0;
  160.         c->local_wfd.is_socket=0; /* TODO: It's not always true */
  161. #ifdef USE_WIN32
  162.         if(get_last_socket_error()!=ENOTSOCK) {
  163. #else
  164.         if(c->opt->option.transparent || get_last_socket_error()!=ENOTSOCK) {
  165. #endif
  166.             sockerror("getpeerbyname");
  167.             return -1;
  168.         }
  169.         /* Ignore ENOTSOCK error so 'local' doesn't have to be a socket */
  170.     } else {
  171.         safe_ntoa(c->accepting_address, c->addr.sin_addr);
  172.         c->local_rfd.is_socket=1;
  173.         c->local_wfd.is_socket=1; /* TODO: It's not always true */
  174.         /* It's a socket: lets setup options */
  175.         if(set_socket_options(c->local_rfd.fd, 1)<0)
  176.             return -1;
  177.         if(auth_libwrap(c)<0)
  178.             return -1;
  179.         if(auth_user(c)<0) {
  180.             log(LOG_WARNING, "Connection from %s:%d REFUSED by IDENT",
  181.                 c->accepting_address, ntohs(c->addr.sin_port));
  182.             return -1;
  183.         }
  184.         log(LOG_NOTICE, "%s connected from %s:%d", c->opt->servname,
  185.             c->accepting_address, ntohs(c->addr.sin_port));
  186.     }
  187.     return 0; /* OK */
  188. }
  189.  
  190. static int init_remote(CLI *c) {
  191.     int fd;
  192.  
  193.     /* create connection to host/service */
  194.     if(c->opt->local_ip)
  195.         c->bind_ip=*c->opt->local_ip;
  196. #ifndef USE_WIN32
  197.     else if(c->opt->option.transparent)
  198.         c->bind_ip=c->addr.sin_addr.s_addr;
  199. #endif
  200.     else
  201.         c->bind_ip=0;
  202.     /* Setup c->remote_fd, now */
  203.     if(c->opt->option.remote) {
  204.         c->resolved_addresses=NULL;
  205.         fd=connect_remote(c);
  206.         if(c->resolved_addresses) /* allocated */
  207.             free(c->resolved_addresses);
  208.     } else /* NOT in remote mode */
  209.         fd=connect_local(c);
  210.     if(fd<0) {
  211.         log(LOG_ERR, "Failed to initialize remote connection");
  212.         return -1;
  213.     }
  214. #ifndef USE_WIN32
  215.     if(fd>=max_fds) {
  216.         log(LOG_ERR, "Remote file descriptor out of range (%d>=%d)",
  217.             fd, max_fds);
  218.         closesocket(fd);
  219.         return -1;
  220.     }
  221. #endif
  222.     log(LOG_DEBUG, "Remote FD=%d initialized", fd);
  223.     c->remote_fd.fd=fd;
  224.     c->remote_fd.is_socket=1; /* Always! */
  225.     if(set_socket_options(fd, 2)<0)
  226.         return -1;
  227.     return 0; /* OK */
  228. }
  229.  
  230. static int init_ssl(CLI *c) {
  231.     int i, err;
  232.  
  233.     if(!(c->ssl=SSL_new(ctx))) {
  234.         sslerror("SSL_new");
  235.         return -1;
  236.     }
  237. #if SSLEAY_VERSION_NUMBER >= 0x0922
  238.     SSL_set_session_id_context(c->ssl, sid_ctx, strlen(sid_ctx));
  239. #endif
  240.     if(options.option.client) {
  241.         /* Attempt to use the most recent id in the session cache */
  242.         if(ctx->session_cache_head)
  243.             if(!SSL_set_session(c->ssl, ctx->session_cache_head))
  244.                 log(LOG_WARNING, "Cannot set SSL session id to most recent used");
  245.         SSL_set_fd(c->ssl, c->remote_fd.fd);
  246.         SSL_set_connect_state(c->ssl);
  247.     } else {
  248.         if(c->local_rfd.fd==c->local_wfd.fd)
  249.             SSL_set_fd(c->ssl, c->local_rfd.fd);
  250.         else {
  251.            /* Does it make sence to have SSL on STDIN/STDOUT? */
  252.             SSL_set_rfd(c->ssl, c->local_rfd.fd);
  253.             SSL_set_wfd(c->ssl, c->local_wfd.fd);
  254.         }
  255.         SSL_set_accept_state(c->ssl);
  256.     }
  257.  
  258.     /* Setup some values for transfer() function */
  259.     if(options.option.client) {
  260.         c->sock_rfd=&(c->local_rfd);
  261.         c->sock_wfd=&(c->local_wfd);
  262.         c->ssl_rfd=c->ssl_wfd=&(c->remote_fd);
  263.     } else {
  264.         c->sock_rfd=c->sock_wfd=&(c->remote_fd);
  265.         c->ssl_rfd=&(c->local_rfd);
  266.         c->ssl_wfd=&(c->local_wfd);
  267.     }
  268.  
  269.     while(1) {
  270.         if(options.option.client)
  271.             i=SSL_connect(c->ssl);
  272.         else
  273.             i=SSL_accept(c->ssl);
  274.         err=SSL_get_error(c->ssl, i);
  275.         if(err==SSL_ERROR_NONE)
  276.             break; /* ok -> done */
  277.         if(err==SSL_ERROR_WANT_READ) {
  278.             if(waitforsocket(c->ssl_rfd->fd, 0, c->opt->timeout_busy)==1)
  279.                 continue; /* ok -> retry */
  280.             return -1; /* timeout or error */
  281.         }
  282.         if(err==SSL_ERROR_WANT_WRITE) {
  283.             if(waitforsocket(c->ssl_wfd->fd, 1, c->opt->timeout_busy)==1)
  284.                 continue; /* ok -> retry */
  285.             return -1; /* timeout or error */
  286.         }
  287.         if(err==SSL_ERROR_SYSCALL) {
  288.             switch(get_last_socket_error()) {
  289.             case EINTR:
  290.             case EAGAIN:
  291.                 continue; 
  292.             }
  293.         }
  294.         if(options.option.client)
  295.             sslerror("SSL_connect");
  296.         else
  297.             sslerror("SSL_accept");
  298.         return -1;
  299.     }
  300.     print_cipher(c);
  301.     return 0; /* OK */
  302. }
  303.  
  304. static int transfer(CLI *c) { /* transfer data */
  305.     fd_set rd_set, wr_set;
  306.     int num, err, fdno;
  307.     int check_SSL_pending;
  308.     int ready;
  309.     struct timeval tv;
  310.  
  311.     fdno=c->sock_rfd->fd;
  312.     if(c->sock_wfd->fd>fdno) fdno=c->sock_wfd->fd;
  313.     if(c->ssl_rfd->fd>fdno) fdno=c->ssl_rfd->fd;
  314.     if(c->ssl_wfd->fd>fdno) fdno=c->ssl_wfd->fd;
  315.     fdno+=1;
  316.  
  317.     c->sock_ptr=c->ssl_ptr=0;
  318.     sock_rd=sock_wr=ssl_rd=ssl_wr=1;
  319.     c->sock_bytes=c->ssl_bytes=0;
  320.  
  321.     while(((sock_rd||c->sock_ptr)&&ssl_wr)||((ssl_rd||c->ssl_ptr)&&sock_wr)) {
  322.  
  323.         FD_ZERO(&rd_set); /* Setup rd_set */
  324.         if(sock_rd && c->sock_ptr<BUFFSIZE) /* socket input buffer not full*/
  325.             FD_SET(c->sock_rfd->fd, &rd_set);
  326.         if(ssl_rd && (c->ssl_ptr<BUFFSIZE || /* SSL input buffer not full */
  327.                 (c->sock_ptr && SSL_want_read(c->ssl))
  328.                 /* I want to SSL_write but read from the underlying */
  329.                 /* socket needed for the SSL protocol */
  330.                 )) {
  331.             FD_SET(c->ssl_rfd->fd, &rd_set);
  332.         }
  333.  
  334.         FD_ZERO(&wr_set); /* Setup wr_set */
  335.         if(sock_wr && c->ssl_ptr) /* SSL input buffer not empty */
  336.             FD_SET(c->sock_wfd->fd, &wr_set);
  337.         if (ssl_wr && (c->sock_ptr || /* socket input buffer not empty */
  338.                 (c->ssl_ptr<BUFFSIZE && SSL_want_write(c->ssl))
  339.                 /* I want to SSL_read but write to the underlying */
  340.                 /* socket needed for the SSL protocol */
  341.                 )) {
  342.             FD_SET(c->ssl_wfd->fd, &wr_set);
  343.         }
  344.  
  345.         tv.tv_sec=sock_rd ||
  346.             (ssl_wr&&c->sock_ptr) || (sock_wr&&c->ssl_ptr) ?
  347.             c->opt->timeout_idle : c->opt->timeout_close;
  348.         tv.tv_usec=0;
  349.         ready=sselect(fdno, &rd_set, &wr_set, NULL, &tv);
  350.         if(ready<0) { /* Break the connection for others */
  351.             sockerror("select");
  352.             return -1;
  353.         }
  354.         if(!ready) { /* Timeout */
  355.             if(sock_rd) { /* No traffic for a long time */
  356.                 log(LOG_DEBUG, "select timeout: connection reset");
  357.                 return -1;
  358.             } else { /* Timeout waiting for SSL close_notify */
  359.                 log(LOG_DEBUG, "select timeout waiting for SSL close_notify");
  360.                 break; /* Leave the while() loop */
  361.             }
  362.         }
  363.  
  364.         /* Set flag to try and read any buffered SSL data if we made */
  365.         /* room in the buffer by writing to the socket */
  366.         check_SSL_pending = 0;
  367.  
  368.         if(sock_wr && FD_ISSET(c->sock_wfd->fd, &wr_set)) {
  369.             switch(num=writesocket(c->sock_wfd->fd, c->ssl_buff, c->ssl_ptr)) {
  370.             case -1: /* error */
  371.                 switch(get_last_socket_error()) {
  372.                 case EINTR:
  373.                     log(LOG_DEBUG,
  374.                         "writesocket interrupted by a signal: retrying");
  375.                     break;
  376.                 case EWOULDBLOCK:
  377.                     log(LOG_NOTICE, "writesocket would block: retrying");
  378.                     break;
  379.                 default:
  380.                     sockerror("writesocket");
  381.                     return -1;
  382.                 }
  383.                 break;
  384.             case 0:
  385.                 log(LOG_DEBUG, "No data written to the socket: retrying");
  386.                 break;
  387.             default:
  388.                 memmove(c->ssl_buff, c->ssl_buff+num, c->ssl_ptr-num);
  389.                 if(c->ssl_ptr==BUFFSIZE)
  390.                     check_SSL_pending=1;
  391.                 c->ssl_ptr-=num;
  392.                 c->sock_bytes+=num;
  393.                 if(!ssl_rd && !c->ssl_ptr) {
  394.                     shutdown(c->sock_wfd->fd, SHUT_WR);
  395.                     log(LOG_DEBUG,
  396.                         "Socket write shutdown (no more data to send)");
  397.                     sock_wr=0;
  398.                 }
  399.             }
  400.         }
  401.  
  402.         if(ssl_wr && ( /* SSL sockets are still open */
  403.                 (c->sock_ptr && FD_ISSET(c->ssl_wfd->fd, &wr_set)) ||
  404.                 /* See if application data can be written */
  405.                 (SSL_want_read(c->ssl) && FD_ISSET(c->ssl_rfd->fd, &rd_set))
  406.                 /* I want to SSL_write but read from the underlying */
  407.                 /* socket needed for the SSL protocol */
  408.                 )) {
  409.             num=SSL_write(c->ssl, c->sock_buff, c->sock_ptr);
  410.  
  411.             err=SSL_get_error(c->ssl, num);
  412.             switch(err) {
  413.             case SSL_ERROR_NONE:
  414.                 memmove(c->sock_buff, c->sock_buff+num, c->sock_ptr-num);
  415.                 c->sock_ptr-=num;
  416.                 c->ssl_bytes+=num;
  417.                 if(!sock_rd && !c->sock_ptr && ssl_wr) {
  418.                     SSL_shutdown(c->ssl); /* Send close_notify */
  419.                     log(LOG_DEBUG,
  420.                         "SSL write shutdown (no more data to send)");
  421.                     ssl_wr=0;
  422.                 }
  423.                 break;
  424.             case SSL_ERROR_WANT_WRITE:
  425.             case SSL_ERROR_WANT_READ:
  426.             case SSL_ERROR_WANT_X509_LOOKUP:
  427.                 log(LOG_DEBUG, "SSL_write returned WANT_: retrying");
  428.                 break;
  429.             case SSL_ERROR_SYSCALL:
  430.                 if(num<0) { /* really an error */
  431.                     if(get_last_socket_error()==EINTR) {
  432.                         log(LOG_DEBUG, "SSL write interrupted by a signal: retrying");
  433.                         break;
  434.                     }
  435.                     sockerror("SSL_write (ERROR_SYSCALL)");
  436.                     return -1;
  437.                 }
  438.                 break;
  439.             case SSL_ERROR_ZERO_RETURN: /* close_notify received */
  440.                 log(LOG_DEBUG, "SSL closed on SSL_write");
  441.                 ssl_rd=ssl_wr=0;
  442.                 break;
  443.             case SSL_ERROR_SSL:
  444.                 sslerror("SSL_write");
  445.                 return -1;
  446.             default:
  447.                 log(LOG_ERR, "SSL_write/SSL_get_error returned %d", err);
  448.                 return -1;
  449.             }
  450.         }
  451.  
  452.         if(sock_rd && FD_ISSET(c->sock_rfd->fd, &rd_set)) {
  453.             switch(num=readsocket(c->sock_rfd->fd, c->sock_buff+c->sock_ptr, BUFFSIZE-c->sock_ptr)) {
  454.             case -1:
  455.                 switch(get_last_socket_error()) {
  456.                 case EINTR:
  457.                     log(LOG_DEBUG,
  458.                         "readsocket interrupted by a signal: retrying");
  459.                     break;
  460.                 case EWOULDBLOCK:
  461.                     log(LOG_NOTICE, "readsocket would block: retrying");
  462.                     break;
  463.                 default:
  464.                     sockerror("readsocket");
  465.                     return -1;
  466.                 }
  467.                 break;
  468.             case 0: /* close */
  469.                 log(LOG_DEBUG, "Socket closed on read");
  470.                 sock_rd=0;
  471.                 if(!c->sock_ptr && ssl_wr) {
  472.                     SSL_shutdown(c->ssl); /* Send close_notify */
  473.                     log(LOG_DEBUG,
  474.                         "SSL write shutdown (output buffer empty)");
  475.                     ssl_wr=0;
  476.                 }
  477.                 break;
  478.             default:
  479.                 c->sock_ptr += num;
  480.             }
  481.         }
  482.  
  483.         if(ssl_rd && ( /* SSL sockets are still open */
  484.                 (c->ssl_ptr<BUFFSIZE && FD_ISSET(c->ssl_rfd->fd, &rd_set)) ||
  485.                 /* See if there's any application data coming in */
  486.                 (SSL_want_write(c->ssl) && FD_ISSET(c->ssl_wfd->fd, &wr_set)) ||
  487.                 /* I want to SSL_read but write to the underlying */
  488.                 /* socket needed for the SSL protocol */
  489.                 (check_SSL_pending && SSL_pending(c->ssl))
  490.                 /* Write made space from full buffer */
  491.                 )) {
  492.             num=SSL_read(c->ssl, c->ssl_buff+c->ssl_ptr, BUFFSIZE-c->ssl_ptr);
  493.  
  494.             err=SSL_get_error(c->ssl, num);
  495.             switch(err) {
  496.             case SSL_ERROR_NONE:
  497.                 c->ssl_ptr+=num;
  498.                 break;
  499.             case SSL_ERROR_WANT_WRITE:
  500.             case SSL_ERROR_WANT_READ:
  501.             case SSL_ERROR_WANT_X509_LOOKUP:
  502.                 log(LOG_DEBUG, "SSL_read returned WANT_: retrying");
  503.                 break;
  504.             case SSL_ERROR_SYSCALL:
  505.                 if(num<0) { /* not EOF */
  506.                     if(get_last_socket_error()==EINTR) {
  507.                         log(LOG_DEBUG, "SSL read interrupted by a signal: retrying");
  508.                         break;
  509.                     }
  510.                     sockerror("SSL_read (SSL_ERROR_SYSCALL)");
  511.                     return -1;
  512.                 }
  513.                 log(LOG_DEBUG, "SSL socket closed on SSL_read");
  514.                 ssl_rd=ssl_wr=0;
  515.                 break;
  516.             case SSL_ERROR_ZERO_RETURN: /* close_notify received */
  517.                 log(LOG_DEBUG, "SSL closed on SSL_read");
  518.                 ssl_rd=0;
  519.                 if(!c->sock_ptr && ssl_wr) {
  520.                     SSL_shutdown(c->ssl); /* Send close_notify back */
  521.                     log(LOG_DEBUG,
  522.                         "SSL write shutdown (output buffer empty)");
  523.                     ssl_wr=0;
  524.                 }
  525.                 if(!c->ssl_ptr && sock_wr) {
  526.                     shutdown(c->sock_wfd->fd, SHUT_WR);
  527.                     log(LOG_DEBUG,
  528.                         "Socket write shutdown (output buffer empty)");
  529.                     sock_wr=0;
  530.                 }
  531.                 break;
  532.             case SSL_ERROR_SSL:
  533.                 sslerror("SSL_read");
  534.                 return -1;
  535.             default:
  536.                 log(LOG_ERR, "SSL_read/SSL_get_error returned %d", err);
  537.                 return -1;
  538.             }
  539.         }
  540.     }
  541.     return 0; /* OK */
  542. }
  543.  
  544. static void cleanup(CLI *c, int error) {
  545.         /* Cleanup SSL */
  546.     if(c->ssl) { /* SSL initialized */
  547.         SSL_set_shutdown(c->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
  548.         SSL_free(c->ssl);
  549.         ERR_remove_state(0);
  550.     }
  551.         /* Cleanup remote socket */
  552.     if(c->remote_fd.fd>=0) { /* Remote socket initialized */
  553.         if(error && c->remote_fd.is_socket)
  554.             reset(c->remote_fd.fd, "linger (remote)");
  555.         closesocket(c->remote_fd.fd);
  556.     }
  557.         /* Cleanup local socket */
  558.     if(c->local_rfd.fd>=0) { /* Local socket initialized */
  559.         if(c->local_rfd.fd==c->local_wfd.fd) {
  560.             if(error && c->local_rfd.is_socket)
  561.                 reset(c->local_rfd.fd, "linger (local)");
  562.             closesocket(c->local_rfd.fd);
  563.         } else { /* STDIO */
  564.             if(error && c->local_rfd.is_socket)
  565.                 reset(c->local_rfd.fd, "linger (local_rfd)");
  566.             if(error && c->local_wfd.is_socket)
  567.                 reset(c->local_wfd.fd, "linger (local_wfd)");
  568.        }
  569.     }
  570. }
  571.  
  572. static void print_cipher(CLI *c) { /* print negotiated cipher */
  573. #if SSLEAY_VERSION_NUMBER <= 0x0800
  574.     log(LOG_INFO, "%s opened with SSLv%d, cipher %s",
  575.         c->opt->servname, ssl->session->ssl_version, SSL_get_cipher(c->ssl));
  576. #else
  577.     SSL_CIPHER *cipher;
  578.     char buf[STRLEN];
  579.     int len;
  580.  
  581.     cipher=SSL_get_current_cipher(c->ssl);
  582.     SSL_CIPHER_description(cipher, buf, STRLEN);
  583.     len=strlen(buf);
  584.     if(len>0)
  585.         buf[len-1]='\0';
  586.     log(LOG_INFO, "Negotiated ciphers: %s", buf);
  587. #endif
  588. }
  589.  
  590. static int auth_libwrap(CLI *c) {
  591. #ifdef USE_LIBWRAP
  592.     struct request_info request;
  593.     int result;
  594.  
  595.     enter_critical_section(CRIT_LIBWRAP); /* libwrap is not mt-safe */
  596.     request_init(&request,
  597.         RQ_DAEMON, c->opt->servname, RQ_FILE, c->local_rfd.fd, 0);
  598.     fromhost(&request);
  599.     result=hosts_access(&request);
  600.     leave_critical_section(CRIT_LIBWRAP);
  601.  
  602.     if (!result) {
  603.         log(LOG_WARNING, "Connection from %s:%d REFUSED by libwrap",
  604.             c->accepting_address, ntohs(c->addr.sin_port));
  605.         log(LOG_DEBUG, "See hosts_access(5) for details");
  606.         return -1; /* FAILED */
  607.     }
  608. #endif
  609.     return 0; /* OK */
  610. }
  611.  
  612. static int auth_user(CLI *c) {
  613.     struct servent *s_ent;    /* structure for getservbyname */
  614.     struct sockaddr_in ident; /* IDENT socket name */
  615.     int fd;                   /* IDENT socket descriptor */
  616.     char name[STRLEN];
  617.     int retval;
  618.  
  619.     if(!c->opt->username)
  620.         return 0; /* -u option not specified */
  621.     if((fd=socket(AF_INET, SOCK_STREAM, 0))<0) {
  622.         sockerror("socket (auth_user)");
  623.         return -1;
  624.     }
  625.     alloc_fd(fd);
  626.     memcpy(&ident, &c->addr, sizeof(ident));
  627.     s_ent=getservbyname("auth", "tcp");
  628.     if(!s_ent) {
  629.         log(LOG_WARNING, "Unknown service 'auth': using default 113");
  630.         ident.sin_port=htons(113);
  631.     } else {
  632.         ident.sin_port=s_ent->s_port;
  633.     }
  634.     if(connect(fd, (struct sockaddr *)&ident, sizeof(ident))<0) {
  635.         switch(get_last_socket_error()) {
  636.         case EINPROGRESS: /* retry */
  637.             log(LOG_DEBUG, "connect #1 (auth_user): EINPROGRESS: retrying");
  638.             break;
  639.         case EWOULDBLOCK: /* retry */
  640.             log(LOG_DEBUG, "connect #1 (auth_user): EWOULDBLOCK: retrying");
  641.             break;
  642.         default:
  643.             sockerror("connect #1 (auth_user)");
  644.             closesocket(fd);
  645.             return -1;
  646.         }
  647.         if(waitforsocket(fd, 1 /* write */, c->opt->timeout_busy)<1) {
  648.             closesocket(fd);
  649.             return -1;
  650.         }
  651.         if(connect(fd, (struct sockaddr *)&ident, sizeof(ident))<0) {
  652.             switch(get_last_socket_error()) {
  653.             case EINVAL: /* WIN32 is strange... */
  654.                 log(LOG_DEBUG, "connect #2 (auth_user): EINVAL: ok");
  655.             case EISCONN: /* ok */
  656.                 break; /* success */
  657.             default:
  658.                 sockerror("connect #2 (auth_user))");
  659.                 closesocket(fd);
  660.                 return -1;
  661.             }
  662.         }
  663.     }
  664.     log(LOG_DEBUG, "IDENT server connected");
  665.     if(fdprintf(c, fd, "%u , %u",
  666.             ntohs(c->addr.sin_port), ntohs(c->opt->localport))<0) {
  667.         sockerror("fdprintf (auth_user)");
  668.         closesocket(fd);
  669.         return -1;
  670.     }
  671.     if(fdscanf(c, fd, "%*[^:]: USERID :%*[^:]:%s", name)!=1) {
  672.         log(LOG_ERR, "Incorrect data from IDENT server");
  673.         closesocket(fd);
  674.         return -1;
  675.     }
  676.     closesocket(fd);
  677.     retval=strcmp(name, c->opt->username) ? -1 : 0;
  678.     safestring(name);
  679.     log(LOG_INFO, "IDENT resolved remote user to %s", name);
  680.     return retval;
  681. }
  682.  
  683. static int connect_local(CLI *c) { /* spawn local process */
  684. #if defined (USE_WIN32) || defined (__vms)
  685.     log(LOG_ERR, "LOCAL MODE NOT SUPPORTED ON WIN32 and OpenVMS PLATFORM");
  686.     return -1;
  687. #else /* USE_WIN32, __vms */
  688.     char env[3][STRLEN], name[STRLEN];
  689.     int fd[2], pid;
  690.     X509 *peer;
  691. #ifdef HAVE_PTHREAD_SIGMASK
  692.     sigset_t newmask;
  693. #endif
  694.     if (c->opt->option.pty) {
  695.         char tty[STRLEN];
  696.  
  697.         if(pty_allocate(fd, fd+1, tty, STRLEN)) {
  698.             return -1;
  699.         }
  700.         log(LOG_DEBUG, "%s allocated", tty);
  701.     } else {
  702.         if(make_sockets(fd))
  703.             return -1;
  704.     }
  705.     pid=fork();
  706.     c->pid=(unsigned long)pid;
  707.     switch(pid) {
  708.     case -1:    /* error */
  709.         closesocket(fd[0]);
  710.         closesocket(fd[1]);
  711.         ioerror("fork");
  712.         return -1;
  713.     case  0:    /* child */
  714.         closesocket(fd[0]);
  715.         dup2(fd[1], 0);
  716.         dup2(fd[1], 1);
  717.         if(!options.option.foreground)
  718.             dup2(fd[1], 2);
  719.         closesocket(fd[1]);
  720.         safecopy(env[0], "REMOTE_HOST=");
  721.         safeconcat(env[0], c->accepting_address);
  722.         putenv(env[0]);
  723.         if(c->opt->option.transparent) {
  724.             putenv("LD_PRELOAD=" LIBDIR "/libstunnel.so");
  725.             /* For Tru64 _RLD_LIST is used instead */
  726.             putenv("_RLD_LIST=" LIBDIR "/libstunnel.so:DEFAULT");
  727.         }
  728.         if(c->ssl) {
  729.             peer=SSL_get_peer_certificate(c->ssl);
  730.             if(peer) {
  731.                 safecopy(env[1], "SSL_CLIENT_DN=");
  732.                 X509_NAME_oneline(X509_get_subject_name(peer), name, STRLEN);
  733.                 safestring(name);
  734.                 safeconcat(env[1], name);
  735.                 putenv(env[1]);
  736.                 safecopy(env[2], "SSL_CLIENT_I_DN=");
  737.                 X509_NAME_oneline(X509_get_issuer_name(peer), name, STRLEN);
  738.                 safestring(name);
  739.                 safeconcat(env[2], name);
  740.                 putenv(env[2]);
  741.                 X509_free(peer);
  742.             }
  743.         }
  744. #ifdef HAVE_PTHREAD_SIGMASK
  745.         sigemptyset(&newmask);
  746.         sigprocmask(SIG_SETMASK, &newmask, NULL);
  747. #endif
  748.         execvp(c->opt->execname, c->opt->execargs);
  749.         ioerror(c->opt->execname); /* execv failed */
  750.         _exit(1);
  751.     default:
  752.         break;
  753.     }
  754.     /* parent */
  755.     log(LOG_INFO, "Local mode child started (PID=%lu)", c->pid);
  756.     closesocket(fd[1]);
  757. #ifdef FD_CLOEXEC
  758.     fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  759. #endif
  760.     return fd[0];
  761. #endif /* USE_WIN32,__vms */
  762. }
  763.  
  764. #ifndef USE_WIN32
  765.  
  766. static int make_sockets(int fd[2]) { /* make pair of connected sockets */
  767. #ifdef INET_SOCKET_PAIR
  768.     struct sockaddr_in addr;
  769.     int addrlen;
  770.     int s; /* temporary socket awaiting for connection */
  771.  
  772.     if((s=socket(AF_INET, SOCK_STREAM, 0))<0) {
  773.         sockerror("socket#1");
  774.         return -1;
  775.     }
  776.     if((fd[1]=socket(AF_INET, SOCK_STREAM, 0))<0) {
  777.         sockerror("socket#2");
  778.         return -1;
  779.     }
  780.     addrlen=sizeof(addr);
  781.     memset(&addr, 0, addrlen);
  782.     addr.sin_family=AF_INET;
  783.     addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
  784.     addr.sin_port=0; /* dynamic port allocation */
  785.     if(bind(s, (struct sockaddr *)&addr, addrlen))
  786.         log_error(LOG_DEBUG, get_last_socket_error(), "bind#1");
  787.     if(bind(fd[1], (struct sockaddr *)&addr, addrlen))
  788.         log_error(LOG_DEBUG, get_last_socket_error(), "bind#2");
  789.     if(listen(s, 5)) {
  790.         sockerror("listen");
  791.         return -1;
  792.     }
  793.     if(getsockname(s, (struct sockaddr *)&addr, &addrlen)) {
  794.         sockerror("getsockname");
  795.         return -1;
  796.     }
  797.     if(connect(fd[1], (struct sockaddr *)&addr, addrlen)) {
  798.         sockerror("connect");
  799.         return -1;
  800.     }
  801.     if((fd[0]=accept(s, (struct sockaddr *)&addr, &addrlen))<0) {
  802.         sockerror("accept");
  803.         return -1;
  804.     }
  805.     closesocket(s); /* don't care about the result */
  806. #else
  807.     if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
  808.         sockerror("socketpair");
  809.         return -1;
  810.     }
  811. #endif
  812.     return 0;
  813. }
  814. #endif
  815.  
  816. static int connect_remote(CLI *c) { /* connect to remote host */
  817.     struct sockaddr_in addr;
  818.     u32 *list;
  819.     int error;
  820.     int s; /* destination socket */
  821.     u16 dport;
  822.    
  823.     memset(&addr, 0, sizeof(addr));
  824.     addr.sin_family=AF_INET;
  825.  
  826.     if(c->opt->option.delayed_lookup) {
  827.         if(name2nums(c->opt->remote_address, "127.0.0.1",
  828.                 &c->resolved_addresses, &dport)==0) {
  829.             /* No host resolved */
  830.             return -1;
  831.         }
  832.         list=c->resolved_addresses;
  833.     } else { /* Use pre-resolved addresses */
  834.         list=c->opt->remotenames;
  835.         dport=c->opt->remoteport;
  836.     }
  837.  
  838.     /* connect each host from the list */
  839.     for(; *list+1; list++) { /* same as (signed)*list!=-1 */
  840.         if((s=socket(AF_INET, SOCK_STREAM, 0))<0) {
  841.             sockerror("remote socket");
  842.             return -1;
  843.         }
  844.         if(alloc_fd(s))
  845.             return -1;
  846.  
  847.         if(c->bind_ip) { /* explicit local bind or transparent proxy */
  848.             addr.sin_addr.s_addr=c->bind_ip;
  849.             addr.sin_port=htons(0);
  850.             if(bind(s, (struct sockaddr *)&addr, sizeof(addr))<0) {
  851.                 sockerror("bind transparent");
  852.                 closesocket(s);
  853.                 return -1;
  854.             }
  855.         }
  856.  
  857.         /* try to connect for the 1st time */
  858.         addr.sin_port=dport;
  859.         addr.sin_addr.s_addr=*list;
  860.         safe_ntoa(c->connecting_address, addr.sin_addr);
  861.         log(LOG_DEBUG, "%s connecting %s:%d", c->opt->servname,
  862.             c->connecting_address, ntohs(addr.sin_port));
  863.         if(!connect(s, (struct sockaddr *)&addr, sizeof(addr)))
  864.             return s; /* no error -> success */
  865.         error=get_last_socket_error();
  866.         switch(error) {
  867.         case EINPROGRESS: /* retry */
  868.             log(LOG_DEBUG, "remote connect #1: EINPROGRESS: retrying");
  869.             break;
  870.         case EWOULDBLOCK: /* retry */
  871.             log(LOG_DEBUG, "remote connect #1: EWOULDBLOCK: retrying");
  872.             break;
  873.         default:
  874.             log(LOG_ERR, "remote connect #1 (%s:%d): %s (%d)",
  875.                 c->connecting_address, ntohs(addr.sin_port),
  876.                 my_strerror(error), error);
  877.             closesocket(s);
  878.             continue; /* Next IP */
  879.         }
  880.  
  881.         /* wait until the connecting socket is ready for write */
  882.         if(waitforsocket(s, 1 /* write */, c->opt->timeout_busy)<1) {
  883.             closesocket(s);
  884.             continue; /* timeout or error */
  885.         }
  886.  
  887.         /* try to connect for the 2nd time */
  888.         if(!connect(s, (struct sockaddr *)&addr, sizeof(addr)))
  889.             return s; /* no error -> success */
  890.         error=get_last_socket_error();
  891.         switch(error) {
  892.         case EINVAL: /* WIN32 is strange... */
  893.             log(LOG_DEBUG, "remote connect #2: EINVAL: ok");
  894.         case EISCONN: /* ok */
  895.             return s; /* success */
  896.         default:
  897.             log(LOG_ERR, "remote connect #2 (%s:%d): %s (%d)",
  898.                 c->connecting_address, ntohs(addr.sin_port),
  899.                 my_strerror(error), error);
  900.             closesocket(s);
  901.             continue; /* Next IP */
  902.         }
  903.     }
  904.     return -1;
  905. }
  906.  
  907. static void reset(int fd, char *txt) {
  908.     /* Set lingering on a socket if needed*/
  909.     struct linger l;
  910.  
  911.     l.l_onoff=1;
  912.     l.l_linger=0;
  913.     if(setsockopt(fd, SOL_SOCKET, SO_LINGER, (void *)&l, sizeof(l)))
  914.         log_error(LOG_DEBUG, get_last_socket_error(), txt);
  915. }
  916.  
  917. /* End of client.c */
  918.